package com.example.demo.Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncodeMD5 {
  public static String encodeMD5(File file){
    FileInputStream in = null;
    String value = null;
    try {
      in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    try {
      MappedByteBuffer mbf = in.getChannel().map(FileChannel.MapMode.READ_ONLY,0,file.length());
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(mbf);
      BigInteger bi = new BigInteger(1, md5.digest());
      value = bi.toString(16);
    } catch (IOException | NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    finally {
      if(in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return value;
  }
}
